#include "Glyph.h"



GlyphData::GlyphData() :error(nullptr)
{
}

bool GlyphData::LoadGlyph(const char* strTypeface, int point_size, int dpi)
{
	fprintf(stdout, "Loading font - %s \n", strTypeface);
	if (!IntiliazeFont(strTypeface, point_size, dpi))
		return false;

	glyph = face->glyph;
	return true;
}

void GlyphData::InitiliazeChars(char * source)
{
	FT_UInt  glyph_index;
	Data gd;
	for (source; *source != '\0'; source++)
	{
		glyph_index = FT_Get_Char_Index(face, *source);/* retrieve glyph index from character code */

		if (FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT))/* load glyph image into the slot (erase previous one) */
		{
			fprintf(stderr, "Could not load character %s\n", *source);
			return;
		}

		if (FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL))/* convert to an anti-aliased bitmap */
		{
			fprintf(stderr, "Could not convert to an anti-aliased bitmap - %s\n", *source);
			return;
		}

		// init the gd.bitmap_buffer array to be the size needed
		gd.bitmap_buffer = new unsigned char[glyph->bitmap.rows * glyph->bitmap.width];
		// copy the texture data from 'glyph' to 'gd'
		memcpy(gd.bitmap_buffer, glyph->bitmap.buffer, glyph->bitmap.rows * glyph->bitmap.width);

		gd.bitmap_width = glyph->bitmap.width; // copy texture width
		gd.bitmap_rows = glyph->bitmap.rows; // copy texture height
		gd.bitmap_left = glyph->bitmap_left; // copy glyph width (pixels)
		gd.bitmap_top = glyph->bitmap_top; // copy glyph height (pixels)
		gd.advance = glyph->advance; // copy the advance vector (note this isn't c++ vector, this is real vector)
		gd.c = *source; // set the character
		//gd.size = currentsize; // set the size

		glyphs.push_back(gd); // put gd into 'glyphs' vector for later reuse
	}
}
bool GlyphData::IntiliazeFont(const char* strTypeface, int point_size, int dpi)
{
	if (FT_Init_FreeType(&library))
	{

		error = "Error loading Freetype library\n";
		return false;
	}


	if (FT_New_Face(library, strTypeface, 0, &face))
	{

		error = "Error loading font \n";
		return false;
	}


	if (FT_Set_Char_Size(face, point_size * 64, point_size * 64, dpi, dpi)) {
		error = "Error initializing character parameters\n";
		return false;
	}
	return true;
}


GlyphData::~GlyphData()
{

}